import {
  mapGetters
} from 'vuex'

// import { crmLeadsNumAPI, crmLeadsStarAPI } from '@/api/crm/leads'
// import { crmCustomerNumAPI, crmCustomerStarAPI } from '@/api/crm/customer'
// import { crmContactsNumAPI, crmContactsStarAPI } from '@/api/crm/contacts'
// import {
//   crmBusinessNumAPI,
//   crmBusinessStarAPI
// } from '@/api/crm/business'
// import {
//   crmFlowQueryFlowSettingListAPI,
//   filedGetInformationAPI
// } from '@/api/crm/common'
// import { crmContractNumAPI } from '@/api/crm/contract'
// import { crmProductNumAPI } from '@/api/crm/product'
// import { crmReceivablesNumAPI } from '@/api/crm/receivables'

// import DetailHeadBase from '../components/DetailHeadBase'
// import WkHeadSection from '@/components/NewCom/WkHeadSection'
// import WkSectionItem from '@/components/NewCom/WkHeadSection/SectionItem'

// import crmTypeModel from '@/views/crm/model/crmTypeModel'
import { debounce } from 'throttle-debounce'

export default {
  data() {
    return {
      showFirstDetail: true,
      detailData: null,
      // tabs Number
      tabsNumber: {},
      currentPageIndex: 0,
      // 阶段状态数据
      status: { settingList: [] },
      // 标签信息
      tagInfo: null,
      // 判断内容是否滚动
      bodyIsScroll: false
    }
  },
  props: {
    /** 是公海 默认是客户 */
    isSeas: {
      type: Boolean,
      default: false
    },
    pageIndex: [String, Number],
    pageList: Array // 用于详情切换
  },

  // components: {
  //   DetailHeadBase,
  //   WkHeadSection,
  //   WkSectionItem
  // },

  computed: {
    ...mapGetters(['crm']),
    // 是否能新建跟进记录
    canCreateFollowRecord() {
      return this.crm && this.crm.followRecord && this.crm.followRecord.save
    },
    // 能否查看详情
    canShowDetail() {
      if (this.detailData && this.detailData.dataAuth === 0) {
        return false
      }

      return this.crm && this.crm[this.crmType] && this.crm[this.crmType].read
    },

    showTabsNumber() {
      return this.crmType !== 'marketing' && this.crmType !== 'visit'
    },

    // 是否展示阶段
    statusShow() {
      return this.status.settingList.length > 0
    }
  },

  watch: {
    id: function() {
      if (this.canShowDetail) {
        this.detailData = null
        this.tabsNumber = {}
        this.getDetial()
        this.getTagInfo()
        this.getStatusById(false)
        this.getTabsNum()
      }
    },
    tabCurrentName() {
      this.debouncedGetTabsNum()
    }
  },

  mounted() {
    this.debouncedGetTabsNum = debounce(300, this.getTabsNum)

    this.debouncedExecuteChildScroll = debounce(500, this.executeChildScroll)
  },

  beforeDestroy() {
    this.$bus.$off('crm-tab-num-update', this.debouncedGetTabsNum)
  },

  methods: {
    /**
     * 滚动
     */
    bodyScroll(e) {
      this.bodyIsScroll = e.target.scrollTop > 2

      this.debouncedExecuteChildScroll(this.tabCurrentName)
    },

    /**
     *  执行子组件滚动
     * @param {*} isfirst
     * @returns
     */
    executeChildScroll(ref) {
      const com = this.$refs[ref] ? this.$refs[ref][0] : null
      com && com.scroll && com.scroll()
    },

    /**
     * 获取阶段状态
     */
    getStatusById(isfirst = true) { // isfirst：true 首次打开详情如果有阶段 选中阶段记录
      if (this.crmType === 'marketing') return
      this.loading = true
      crmFlowQueryFlowSettingListAPI({
        label: crmTypeModel[this.crmType],
        typeId: this.id
      })
        .then(res => {
          this.loading = false
          this.status = res.data // 判断阶段是否展示  计算属性
          // if (this.statusShow && isfirst) {
          //   this.tabCurrentName = 'RelativeStageRecords'
          // } else if (!this.statusShow && this.tabCurrentName == 'RelativeStageRecords') {
          //   this.tabCurrentName = this.tabNames.length > 0 ? this.tabNames[0].name : ''
          // }
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 获取标签字段
    */
    getTagInfo() {
      if (this.crmType === 'marketing' || this.isSeas) return
      const params = {
        types: crmTypeModel[this.crmType],
        id: this.id
      }
      if (this.poolId) {
        params.poolId = this.poolId
      }
      filedGetInformationAPI(params)
        .then(res => {
          res.data.forEach(item => {
            if (item.formType == 'field_tag') {
              this.tagInfo = item
            }
          })
        })
        .catch(() => {

        })
    },
    /**
     * 详情页面切换
     */
    pageChange(type) {
      // if (type === 'left') {
      //   if (this.pageIndex > 0) {
      //     let pageIndex = this.pageIndex
      //     this.$emit('update:pageIndex', --pageIndex)
      //     this.$emit('update:id', this.pageList[pageIndex][`${this.crmType}Id`])
      //   } else {
      //     this.$message.error('没有更多了')
      //   }
      // } else {
      //   if (this.pageIndex < this.pageList.length - 1) {
      //     let pageIndex = this.pageIndex
      //     this.$emit('update:pageIndex', ++pageIndex)
      //     this.$emit('update:id', this.pageList[pageIndex][`${this.crmType}Id`])
      //   } else {
      //     this.$message.error('没有更多了')
      //   }
      // }
      this.$message.error('没有更多了')
    },

    viewAfterEnter() {
      if (this.canShowDetail) {
        this.getDetial()
        this.getStatusById()
        this.getTagInfo()
        this.getTabsNum()
        this.$bus.on('crm-tab-num-update', this.debouncedGetTabsNum)
      }
    },

    /**
     * 顶部头 操作
     * @param {*} data
     */
    detailHeadHandle(data) {
      // 返回值为false 不继续执行
      if (this.detailHeadHandleClick(data) === false) {
        return
      }

      if (data.type === 'edit') {
        this.isCreate = true
      } else if (data.type === 'delete' ||
      data.type === 'exit-team' ||
      data.type === 'alloc' ||
      data.type === 'get' ||
      data.type === 'transfer' ||
      data.type === 'transform' ||
      data.type === 'delete' ||
      data.type === 'put_seas') {
        this.hideView()
      } else if (data.type === 'state_start' ||
      data.type === 'state_disable' ||
      data.type === 'deal_status' ||
      data.type === 'cancel' ||
      data.type === 'examine') {
        this.getDetial()
      } else if (data.type === 'save-success') {
        // 但字段编辑成功刷新
        this.editSaveSuccess()
        this.getTagInfo()
        return
      } else if (data.type == 'tag_change') { // 标签操作
        this.getTagInfo()
        if (this.crmType == 'leads') {
          this.getBaseInfo()
        }
        // 改变重要信息
        // if (this.$refs.chiefly) {
        //   this.$refs.chiefly.getBaseInfo()
        // }
        // 改变基本信息
        if (this.tabCurrentName === 'CRMEditBaseInfo') {
          this.$refs.CRMEditBaseInfo[0].getBaseInfo(false)
        }
      } else if (data.type == 'stage-change') {
        this.detailData = null
        this.getDetial()
      }
      this.$emit('handle', data)
    },

    /**
     * 详情操作
     */
    detailHeadHandleClick() {},

    /**
     * 编辑成功
     */
    editSaveSuccess() {
      this.$bus.$emit('crm-detail-update', this.crmType)
      this.$emit('handle', { type: 'save-success' })
      this.detailData = null
      this.getDetial()
      this.getTagInfo()
    },

    /**
     * 获取tab数量
     */
    getTabsNum() {
      if (!this.showTabsNumber) {
        return
      }
      const request = {
        leads: crmLeadsNumAPI,
        customer: crmCustomerNumAPI,
        contacts: crmContactsNumAPI,
        business: crmBusinessNumAPI,
        contract: crmContractNumAPI,
        product: crmProductNumAPI,
        receivables: crmReceivablesNumAPI
      }[this.crmType]

      if (!request) {
        return
      }

      const params = {}
      params['id'] = this.id

      request(params)
        .then(res => {
          this.tabsNumber = res.data || {}
        })
        .catch(() => {
        })
    },

    /**
     * 获取tabs名字
     * @param {*} name
     * @param {*} num
     */
    getTabName(name, num) {
      return `${name}${num && num > 0 ? '（' + num + '）' : ''}`
    },

    /**
     * 切换关注状态
     * @param index
     * @param status
     */
    toggleStar() {
    //   this.loading = true

    //   const request = {
    //     leads: crmLeadsStarAPI,
    //     customer: crmCustomerStarAPI,
    //     contacts: crmContactsStarAPI,
    //     business: crmBusinessStarAPI
    //   }[this.crmType]

    //   const params = {}
    //   params['id'] = this.detailData[`${this.crmType}Id`]
    //   request(params).then(() => {
    //     this.loading = false
    //     this.$message.success(this.detailData.star > 0 ? '取消关注成功' : '关注成功')
    //     this.detailData.star = this.detailData.star > 0 ? 0 : 1
    //     this.$emit('handle', { type: 'star' })
    //   }).catch(() => {
    //     this.loading = false
    //   })
    }
  },

  deactivated: function() { }

}
